package com.lou.springboot.controller;

import com.lou.springboot.dao.UserDao;
import com.lou.springboot.entity.User;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class MyBatisController {

    @Resource
    private UserDao userDao;

    // 查询所有记录
    @GetMapping("/users/mybatis/queryAll")
    public List<User> queryAll(){
        return userDao.findAllUsers();
    }

    @PostMapping("/users/mybatis/insert")
    public String insert(String name,String password){
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            return "名称或密码为空";
        }
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        return userDao.insertUser(user) > 0 ? "添加记录成功":"添加记录失败";
    }

    @PostMapping("/users/mybatis/update")
    public String update(Integer id, String name, String password){
        if (id == null || StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            return "id或姓名或密码为空";
        } else {
            User user = new User();
            user.setId(id);
            user.setName(name);
            user.setPassword(password);
            return userDao.updateUser(user) > 0 ? "更新记录成功":"更新记录失败";
        }
    }

    @DeleteMapping("/users/mybatis/delete")
    public String delete(Integer id){
        if (id == null || id < 1) {
            return "id必须是大于零的正整数";
        } else {
            return userDao.deleteUser(id) > 0 ?" 删除成功":"删除失败";
        }
    }
}
